#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

""" time stepper of dirichlet boundary value problem """

from scipy import linspace, zeros, arange
from scipy.sparse.construct import spdiags
from scipy.sparse.linalg import spsolve as spsolve

from TimeStepper import TimeStepper

import time
import logging


class DirichletTimeStepper(TimeStepper):
    """ time stepper for general convection-diffusion-reaction equation."""

    __slots__ = ['m_lbc', 'm_rbc', 'm_time_solu', 'm_impl_mat', 'm_expl_mat']


    def __init__(self, method='cn'):
        """instantiate object of type Dirichlet time stepper."""
        TimeStepper.__init__(self, method)
        (self.m_lbc, self.m_rbc) = (None, None)
        (self.m_time_solu, self.m_impl_mat, self.m_expl_mat) = (None,
                None, None)

    def _solve_fwd(self, rhs):
        """solve implicit problem."""

        return spsolve(self.m_impl_mat, rhs)

    def __theta_stepper(self, tmp_solu, mass_bd, stiff_bd, i):
        """step using theta method."""

        tmp_solu = self.m_expl_mat * tmp_solu


        theta = self.get_theta()

        (lbc_prev, rbc_prev) = (self.m_lbc[i - 1], self.m_rbc[i - 1])
        (lbc_current, rbc_current) = (self.m_lbc[i], self.m_rbc[i])

        tmp_solu[0] += (lbc_prev - lbc_current) * mass_bd[0, 0] \
            + (theta * lbc_prev + (1 - theta) * lbc_current) \
            * stiff_bd[0, 0]
        tmp_solu[-1] += (rbc_prev - rbc_current) * mass_bd[0, 1] \
            + (theta * rbc_prev + (1 - theta) * rbc_current) \
            * stiff_bd[0, 1]

        if 2 == mass_bd[:, 0].size:
            tmp_solu[1] += (lbc_prev - lbc_current) * mass_bd[1, 0] \
                + (theta * lbc_prev + (1 - theta) * lbc_current) \
                * stiff_bd[1, 0]

            tmp_solu[-2] += (rbc_prev - rbc_current) * mass_bd[1, 1] \
                + (theta * rbc_prev + (1 - theta) * rbc_current) \
                * stiff_bd[1, 1]

        return self._solve_fwd(tmp_solu)

    def _init_engine(self):
        """virtual method."""

        pass

    def __set_up_problem(self):
        """set up time marching scheme."""

        # bwd, fwd matrices.

        init_solu = self.get_initial_state()
        solu_size = init_solu.size
        delta_t = (self.get_expiry() - self.get_start_time()) \
            / self.get_nsteps()
        theta = self.get_theta()

        mdiags = self.get_mass_matrix()
        sdiags = self.get_stiffness_matrix()
        dposi = self.get_diag_posi()

        fwd_diag_mat = mdiags - (1.0 - theta) * delta_t \
            * sdiags
        bwd_diag_mat = mdiags + theta * delta_t * sdiags
        self.m_impl_mat = spdiags(fwd_diag_mat, dposi, solu_size,
                                  solu_size, format='csr')
        self.m_expl_mat = spdiags(bwd_diag_mat, dposi, solu_size,
                                  solu_size, format='csr')

        self._init_engine()

        # boundary conditions in time

        dtime = linspace(self.get_start_time(), self.get_expiry(),
                         self.get_nsteps() + 1, 'True')

        (left_point, right_point) = self.get_left_right()
        self.m_lbc = self.eval_left_bc(left_point, dtime)
        self.m_rbc = self.eval_right_bd_cond(right_point,
                dtime)

        if self.keep_history():
            self.m_time_solu = zeros((self.m_lbc.size, init_solu.size
                    + 2), 'float64')
            self.m_time_solu[0, 1:-1] = init_solu.flatten()
            self.m_time_solu[:, 0] = self.m_lbc.flatten()
            self.m_time_solu[:, -1] = self.m_rbc.flatten()

        return delta_t

    def get_history(self):
        """ get solution at each time step. """

        return self.m_time_solu

    def get_impl_mat(self):
        """ return matix for impl step. """

        return self.m_impl_mat

    def step(self):
        """ march in time. ( solve the bvp )"""

        delta_t = self.__set_up_problem()

        start = time.time()
        tmp_solu = self.get_initial_state().copy()

        (mass_bd, stiff_bd) = self.get_mass_stiff_at_bd()
        stiff_bd = delta_t * stiff_bd

        for i in arange(1, self.get_nsteps() + 1):
            tmp_solu = self.__theta_stepper(tmp_solu, mass_bd,
                    stiff_bd, i)
            if self.keep_history():
                self.m_time_solu[i, 1:-1] = tmp_solu.flatten()

        if self.time_stepper_log():
            log_progress = logging.getLogger('log_progress')
            log_progress.info('Time Stepping     takes '
                              + str(time.time() - start) + ' secs')

        solution = zeros((tmp_solu.size + 2, 1))
        solution[1:-1, 0] = tmp_solu.flatten()
        solution[0, 0] = self.m_lbc[-1]
        solution[-1, 0] = self.m_rbc[-1]
        return solution


